import React from 'react';
import {Modal, Form, Input, InputNumber, Switch, Alert, Row, Col} from 'antd';
import _ from 'lodash';
import form, {emptyRule} from '../_/form';
import redux from '../_/redux';
import {context} from '../_';
import py from '../_/pinyin';
import {app} from '../app';
import _name, {_title} from './dev';
import EditorWs from './editorWs';
import EditorMd from './editorMd';
const FormItem = Form.Item;
const dataName = 'dataEdit';

@context('params')
@form({
    data: dataName,
    newData: {
        Status: true,
        DisplayOrder: 0
    }
})
@redux(_name, {
    data: ({[dataName]: data}) => (data ? data.Id : '-'),
    actions: ['create', 'modify']
})
@redux('app', {
    data: 'cfg.width',
    prefix: 'app'
})
export default class EditorModel extends React.Component {
    state = {ws: {}};

    componentWillReceiveProps(props) {
        const {[dataName]: data} = props;
        const {[dataName]: rawdata} = this.props;
        if (data !== rawdata) {
            this.reset(data);
        }
    }

    onState = (flag, ...args) => {
        switch (flag) {
            //添加工作站
        case 'wsadd': {
            const {ws} = this.state;
            _.each(args[1], i => {
                ws[i] = ws[i] || {};
            });
            this.setState({ws, wsId: args[0]});
            break;
        }
            //移除工作站
        case 'wsremove': {
            let {ws} = this.state;
            ws = _.omit(ws, args[1]);
            this.setState({ws, wsId: args[0]});
            break;
        }
            //切换工作站
        case 'wsactive': {
            this.setState({wsId: args[0]});
            break;
        }
            //模块操作命令发生改变
        case 'mdchange': {
            const {ws, wsId} = this.state;
            ws[wsId] = args[0];
            this.setState({ws});
            break;
        }
        }
    }

    reset = (data) => {
        const ws = JSON.parse(data.AuthData || '{}');
        const wsIds = _.map(ws, (v, k) => parseInt(k));
        this.setState({ws, wsIds, errMsg: false});
    }

    render() {
        const {[dataName]: data = {}, form, onState} = this.props;
        const {ws, wsIds, wsId} = this.state;
        const mdSels = ws[wsId];//_.clone(ws[wsId]);//WARNING:??为什么必须为新对象才能render相关组件
        const {getFieldDecorator: fp} = form;
        const formItemLayout = {
            labelCol: {span: 6},
            wrapperCol: {span: 18},
        };
        const onOk = () => {
            form.validateFieldsAndScroll((err, vals) => {
                if (err) {
                    this.setState({errMsg: true});
                } else {
                    this.setState({errMsg: false});
                    vals.AuthData = JSON.stringify(this.state.ws);
                    onState("save", vals);
                    if (this.props.isNew) {
                        this.props.create(vals, this.props);
                    } else {
                        this.props.modify(vals, this.props);
                    }
                }
            });
        };
        const onCancel = () => {
            form.setFieldsValue(data);
            onState("cancel");
            this.reset(data);
        };

        const nameInputOption = {
            rules: [{min: 1, max: 200}, emptyRule('请输入角色名称!')],
            onChange: (e) => {
                if (this.props.isNew) {
                    const value = e.target.value;
                    form.setFieldsValue({NameJp: value ? py(value) : value});
                }
            }
        };

        const alert = this.state.errMsg ?
            (<Alert message="输入项有错误,请检查后再试!" type="error" showIcon/>)
            : "";

        const width = Math.min(app.maxWidthModal, this.props.appdata - 10);
        const colOpts = {
            xs: {span: 24},
            sm: {span: 12}
        };
        return (
            <Modal
                width={width}
                okText="保存"
                maskClosable={false}
                onOk={onOk}
                onCancel={onCancel}
                wrapClassName={`${_name}Modal`}
                {...this.props}
            >
                {alert}
                <Form>
                    {fp("Id")(<Input type="hidden"/>)}
                    <Row>
                        <Col {...colOpts}>
                            <FormItem {...formItemLayout} label={`${_title}名称`}>
                                {fp("Name", nameInputOption)(<Input />)}
                            </FormItem>
                        </Col>
                        <Col {...colOpts}>
                            <FormItem {...formItemLayout} label="检索码">
                                {fp("NameJp", {rules: [{min: 1, max: 500}, emptyRule('请输入患者姓名!')]})(<Input/>)}
                            </FormItem>
                        </Col>
                        <Col {...colOpts}>
                            <FormItem {...formItemLayout} label="注释">
                                {fp("Comment", {rules: [{min: 1, max: 500}]})(
                                    <Input type="textarea" style={{height: 88}}/>
                                )}
                            </FormItem>
                        </Col>
                        <Col {...colOpts}>
                            <FormItem {...formItemLayout} label="显示顺序">
                                {fp("DisplayOrder")(<InputNumber />)}
                            </FormItem>
                        </Col>
                        <Col {...colOpts}>
                            <FormItem {...formItemLayout} label="状态">
                                {fp("Status", {valuePropName: 'checked'})(
                                    <Switch checkedChildren={'启动'} unCheckedChildren={'停用'}/>
                                )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={8}>
                            <EditorWs
                                width={width}
                                onState={this.onState}
                                wsIds={wsIds}
                            />
                        </Col>
                        <Col span={15} offset={1}>
                            <EditorMd
                                width={width}
                                onState={this.onState}
                                sels={mdSels}
                            />
                        </Col>
                    </Row>
                </Form>
            </Modal>
        );
    }
}
